﻿using System.Linq;
using Windows.ApplicationModel.Background;

namespace Unread.BackgroundTasks
{
    public sealed class BackgroundTaskRegistrar
    {
        public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint, string taskName, IBackgroundTrigger trigger, IBackgroundCondition condition)
        {
            var existingTask = BackgroundTaskRegistration.AllTasks.Where(t => t.Value.Name == taskName).Select(t => t.Value).SingleOrDefault();
            if (existingTask != null)
                return (BackgroundTaskRegistration)existingTask;

            var builder = new BackgroundTaskBuilder
            {
                Name = taskName,
                TaskEntryPoint = taskEntryPoint
            };
            
            builder.SetTrigger(trigger);

            if (condition != null)
                builder.AddCondition(condition);

            var task = builder.Register();

            return task;
        }
    }
}
